import React, { useState, useEffect } from 'react'
import { FloatingBubble, Card, Tag, Space, Divider, Popover, List, Toast, Empty, Dialog } from 'antd-mobile'
import moment from 'moment'
import { useNavigate } from 'react-router-dom'
import {
    AddCircleOutline,
} from 'antd-mobile-icons'
import db from '../../util/db';
import { type } from '../../util/typeConst'
import clearAllIcon from '../../svg/clear.svg'
export default function Home() {
    const navigate = useNavigate();
    const [data, setData] = useState([]);
    const [mdata, setmData] = useState([]);
    const [allIn, setAllIn] = useState(0);
    const [allPay, setAllPay] = useState(0);
    useEffect(() => {
        console.log('useEffect');
        db.qryAllData(rs => setData(rs));
        db.qryCurrMonthData(rs => setmData(rs));
    }, [])
    useEffect(() => {
        if (mdata?.length > 0) {
            let allPay = mdata.reduce((pre = 0, curr) => {
                return (pre + (curr.type === type.pay ? Number(curr.money) : 0))
            }, 0)
            setAllPay(allPay)
            let allIn = mdata.reduce((pre = 0, curr) => {
                return (pre + (curr.type === type.income ? Number(curr.money) : 0))
            }, 0)
            setAllIn(allIn)
        }

    }, [mdata])

    const setPress = () => {
        alert('设置/清理数据')
    }

    const renderHead = () => {
        return (

            <Card
                headerStyle={{
                    color: '#1677ff',
                }}
                title='本月概况'
            >
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>
                        <div>
                            <div>
                                <div style={{ fontSize: 12 }}>
                                    {`${moment().month() + 1}月结余`}
                                </div>
                                <div style={styles.countTxt}>
                                    {allIn - allPay}
                                </div>
                            </div>
                        </div>
                        <div style={styles.outAndIn}>
                            <Space >
                                <Tag round color='#87d068'>
                                    收入
                                </Tag>
                                <span>{allIn}</span>
                            </Space>
                            <Divider direction='vertical' />
                            <Space>
                                <Tag round color='#ff6430'>
                                    支出
                                </Tag>
                                <span>{allPay}</span>
                            </Space>
                        </div>
                    </div>
                    <div
                        style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}
                        onClick={showClearAllModal}
                    >
                        <img src={clearAllIcon} alt={''} />
                    </div>
                </div>

            </Card>
        )
    }

    const renderDetail = () => {
        if (data?.length > 0) {
            return (
                <List
                    header={`赚钱不易，且行且珍惜`}
                    style={styles.listContainer}
                >
                    {data.map((item, index) => (
                        <List.Item key={index}>
                            <Popover.Menu
                                actions={detailAction}
                                onAction={(e) => {
                                    if (e.key === 'update') {
                                        updateItem(item);
                                    }
                                    if (e.key === 'delete') {
                                        showDel(item);
                                    }
                                }}
                                trigger='click'
                            >
                                <div style={styles.detailContainer}>
                                    <div style={{ display: 'flex', alignItems: 'center' }}>
                                        <div>
                                            <img src={item.detailType.icon} alt={''} />
                                        </div>
                                        <div style={{ display: 'flex', flexDirection: 'column', marginLeft: 3 }}>
                                            <div style={{ fontSize: 12 }}>{item.detailType.cn}</div>
                                            <div style={{ fontSize: 10, color: '#999' }}>{item.remark ?? '-'}</div>
                                        </div>
                                    </div>
                                    <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'flex-end' }}>
                                        <div>{item.type === type.income ? '+' + Number(item.money) : -item.money}</div>
                                        <div style={{ fontSize: 10, color: '#999' }}>{item.time}</div>
                                    </div>
                                </div>
                            </Popover.Menu>
                        </List.Item>

                    ))}
                </List>
            )
        } else {
            return (
                <Card style={styles.listEmptyCard}> <Empty description='暂无数据' /></Card>
            )
        }
    }
    const detailAction = [
        { key: 'update', text: '修改', },
        { key: 'delete', text: '删除', },
    ]
    const showDel = (item) => {
        Dialog.show({
            content: '确认删除?此操作无法撤回',
            closeOnAction: true,
            actions: [
                [
                    {
                        key: 'cancel',
                        text: '取消',
                    },
                    {
                        key: 'delete',
                        text: '删除',
                        bold: true,
                        danger: true,
                        onClick: () => { doDel(item.id) }
                        // 写成箭头函数，直接doDel()的话 ，会直接执行
                    },
                ]
            ]
        })
    }

    const showClearAllModal = () => {
        Dialog.show({
            content: '是否清除所有数据?',
            closeOnAction: true,
            actions: [
                [
                    {
                        key: 'cancel',
                        text: '取消',
                    },
                    {
                        key: 'delete',
                        text: '删除',
                        bold: true,
                        danger: true,
                        onClick: () => {
                            db.clearAll(ret => {
                                setData([])
                                setmData([])
                                setAllIn(0)
                                setAllPay(0)
                            })
                        }
                    },
                ]
            ]
        })
    }

    const doDel = (id) => {
        db.delData(id, (rs) => {
            Toast.show('执行成功')
            setData(rs)
        })
    }
    const updateItem = (item) => {
        console.log(`update:${item}`);
    }
    const renderAddBtn = () => {
        return (
            <FloatingBubble
                onClick={() => { navigate('/add', { replace: true }) }}
                style={{
                    width: '30px',
                    height: '30PX',
                    '--initial-position-right': '10VW',
                    '--edge-distance': '5vh',
                }}
            >
                <AddCircleOutline fontSize={32} />
            </FloatingBubble>
        )
    }
    return (
        <div style={styles.container}>
            {renderHead()}
            {renderDetail()}
            {renderAddBtn()}
        </div >
    )
}

const styles = {
    container: {
        flex: 1,
        padding: 15,
        boxSizing: 'border-box',
    },
    listEmptyCard: {
        marginTop: '3vh'
    },
    listContainer: {
        marginTop: '3%',
        height: '65vh',
        overflow: 'auto'
    },
    countTxt: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#000',
        marginTop: '1vh',
        marginBottom: '1vh'
    },
    outAndIn: {
        flex: 1,
        display: 'flex',
        justifyContent: "flex-start",
        alignItems: 'center',
        marginBottom: '3%'
    },
    detailContainer: {
        display: 'flex',
        justifyContent: 'space-between'
    }
}
